/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.contorller.uct;

import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.cache.util.Validator;
import com.apache.database.model.Page;
import com.apache.portal.common.PortalPlugin;
import com.apache.portal.common.annotion.BeanFactory;
import com.apache.portal.common.restfull.RequestMapping;
import com.apache.portal.common.restfull.ResultFullAnntation;
import com.apache.portal.common.restfull.SupperAction;
import com.apache.portal.common.util.CmdUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:  动态表单对接Action
 *
 * @author dyhou 创建时间：2016-5-17
 */
@SuppressWarnings("serial")
@ResultFullAnntation(name = "infoAction", urlPatterns = { "/info/*" })
public class InfoAction extends SupperAction {

    private PortalPlugin plugin;

    public void init() {
        plugin = (PortalPlugin) BeanFactory.getInstance().getBeans("info");
    }

    protected void doInvoke(HttpServletRequest request, HttpServletResponse response,
            String methodType) throws Exception {
        Method method = doInvoke(this.getClass(), request, response, methodType, "");
        if (null != method) {
            Object obj = method.invoke(this, request, response);
            if (!ToolsUtil.isEmpty(obj)) {
                JSONObject array = JSONObject.fromObject(obj);
                this.outputJson(array.toString(), response, request.getParameter("callback"));
            }
        } else {
            gotoErrorPage(request, response, "请求的Action地址未定义");
        }
    }

    /**
     * 保存sortInfo
     */
    @RequestMapping(value = "saveInfo", method = "post")
    protected ResultMsg saveSortInfo(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ResultMsg msg = null;
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "saveSortInfo");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        return msg;
    }

    /**
     * description:  删除sortInfo(sortId)
     */
    @RequestMapping(value = "delInfo", method = "get")
    protected ResultMsg delSortInfo(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ResultMsg msg = null;
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "delSortInfo");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);// PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        return msg;
    }

    /**
     * description:  创建数据库
     */
    @RequestMapping(value = "createDatabase", method = "post")
    protected ResultMsg createDatabase(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ResultMsg msg = new ResultMsg("F", "数据库创建失败");
        Map<String, String> params = this.getParameterMap(request);
        String useDatasource=StrUtil.doNull(params.get("useDatasource"),"plateform");
        String databaseName = params.get("databaseName");
        if(StrUtil.isNull(databaseName)){
            msg = new ResultMsg("F", "数据库名不能为空！");
            return msg;
        }
        params.put("useDatasource",useDatasource);
        params.put("doCode", "createDatabase");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,params);
        if (entity != null) {
            String entityResult = String.valueOf(entity.getEntity());
            if (StrUtil.isNotNull(entityResult) && "T".equals(entityResult)) {
                msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
            } else {
                msg = new ResultMsg("F", entity.getMessage());
            }
        }
        log.info("数据库创建结果：" + msg);
        return msg;
    }


    /**
     * description:  发布表单（sortId）
     */
    @RequestMapping(value = "publish", method = "get")
    protected ResultMsg publish(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        ResultMsg msg = new ResultMsg("F", "启用失败");
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "publish");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        if (entity != null) {
            String entityResult = String.valueOf(entity.getEntity());
            if (StrUtil.isNotNull(entityResult) && "T".equals(entityResult)) {
                msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
            } else {
                msg = new ResultMsg("F", entity.getMessage());
            }
        }
        log.info("数据表启用结果：" + msg);
        return msg;
    }

    /**
     * description:  停用表单（sortId）
     */
    @RequestMapping(value = "stop", method = "get")
    protected ResultMsg stopInfo(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = this.getParameterMap(request);
        ResultMsg msg = null;
        params.put("doCode", "stop");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);// PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        return msg;
    }

    /**
     * description:  查询表单
     */
    @RequestMapping(value = "listInfo", method = "get")
    protected Object listInfo(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = this.getParameterMap(request);
        Map<String, Object> data = new HashMap<String, Object>();
        params.put("doCode", "listSortInfo");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        if (!ToolsUtil.isEmpty(entity.getEntity())) {
            if (entity.getEntity() instanceof Page) {
                Page pageList = (Page) entity.getEntity();
                data.put("total", pageList.getCount());
                data.put("rows", pageList.getPageObjects());
            } else {
                List list = (List) entity.getEntity();
                data.put("total", list.size());
                data.put("rows", list);
            }
        } else {
            data.put("total", "0");
        }
        return data;
    }

    /**
     * description:  保存元素信息
     */
    @RequestMapping(value = "saveMetadata", method = "post")
    protected ResultMsg saveMetadata(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ResultMsg msg = null;
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "saveMetadata");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        return msg;
    }

    /**
     * description:  删除元素（metadataId,sortId）
     */
    @RequestMapping(value = "delMetadata", method = "get")
    protected ResultMsg delMetadata(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ResultMsg msg = null;
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "delMetadata");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        return msg;
    }

    /**
     * description:  修改用户信息操作
     * 使用页面：editUser.jsp
     */
    @RequestMapping(value = "listMetadata", method = "get")
    protected Object listMetadata(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = this.getParameterMap(request);
        Map<String, Object> data = new HashMap<String, Object>();
        params.put("doCode", "listMetadata");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        if (ToolsUtil.isEmpty(entity.getEntity())) {
            if (entity.getEntity() instanceof Page) {
                Page pageList = (Page) entity.getEntity();
                data.put("total", pageList.getCount());
                data.put("rows", pageList.getPageObjects());
            } else {
                List list = (List) entity.getEntity();
                data.put("total", list.size());
                data.put("rows", list);
            }
        } else {
            data.put("total", "0");
        }
        return data;
    }

    /**
     * description:  保存接口信息
     */
    @RequestMapping(value = "saveProtocol", method = "post")
    protected ResultMsg saveProtocol(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ResultMsg msg = null;
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "saveProtocol");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        log.info("saveProtocol-RPC接口保存结果：" + msg);
        return msg;
    }

    /**
     * description:  接口列表
     */
    @RequestMapping(value = "listProtocol", method = "post")
    protected Object listProtocol(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "listProtocol");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        Map<String, Object> data = new HashMap<String, Object>();
        if (!Validator.isEmpty(entity.getEntity())) {
            Page pageList = (Page) entity.getEntity();
            Map<String, Object> mapData = new HashMap<String, Object>();
            data.put("total", pageList.getCount());
            data.put("rows", pageList.getPageObjects());
        }
        return data;
    }

    //刷新接口缓存
    @RequestMapping(value = "loadCache", method = "post")
    protected ResultMsg loadCache(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ResultMsg msg = null;
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "loadCache");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", "缓存刷新成功");
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        return msg;
    }

    //接口详情
    @RequestMapping(value = "infoProtocol", method = "post")
    protected Object infoProtocol(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "infoProtocol");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        return entity.getEntity();
    }

    /**
     * description:  保存数据源信息
     */
    @RequestMapping(value = "saveDatasource", method = "post")
    protected ResultMsg saveDatasource(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ResultMsg msg = null;
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "saveDatasource");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", String.valueOf(entity.getEntity()));
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        log.info("saveDatasource-数据源保存结果：" + msg);
        return msg;
    }

    /**
     * description:  数据源列表
     */
    @RequestMapping(value = "listDatasource", method = "post")
    protected Object listDatasource(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "listDatasource");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        Map<String, Object> data = new HashMap<String, Object>();
        if (!Validator.isEmpty(entity.getEntity())) {
            Page pageList = (Page) entity.getEntity();
            Map<String, Object> mapData = new HashMap<String, Object>();
            data.put("total", pageList.getCount());
            data.put("rows", pageList.getPageObjects());
        }
        return data;
    }

    //刷新数据源缓存
    @RequestMapping(value = "loadDatasource", method = "post")
    protected ResultMsg loadDatasource(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ResultMsg msg = null;
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "loadDatasource");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", "缓存刷新成功");
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        log.info("loadDatasource-数据源缓存刷新：" + msg);
        return msg;
    }

    //数据源详情
    @RequestMapping(value = "infoDatasource", method = "post")
    protected Object infoDatasource(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "infoDatasource");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response,
                params);//PortalPubFactory.getInstance().getPlugin("info")
        //.doInvoke(request, response, params);
        return entity.getEntity();
    }

    //调用cmd命令执行启动jar包服务
    @RequestMapping(value = "startServerProjet", method = "post")
    protected Object startServerProjet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        Map<String, String> params = this.getParameterMap(request);
        ResultMsg msg = new ResultMsg("F", "服务启动失败");
        String jarName = params.get("jarName");
        if (StrUtil.isNull(jarName)) {
            msg = new ResultMsg("T", "启动的jar文件路径不能为空！！");
            return msg;
        }
        log.info("本次操作JAR文件：" + jarName);
        //String cmd_startJar="java -jar D:\\WorkspacesGit\\plateform\\product\\apache-rpc-server\\target\\apache-rpc-server-3.0.1-SNAPSHOT.jar";
        String cmd_startJar = "java -jar " + jarName;
        try {
            String reuslt = CmdUtils.exeCmd(cmd_startJar);
            System.out.println(reuslt);
            msg = new ResultMsg("T", "启动成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return msg;
    }

    /**
     * 保存sortInfo
     */
    @RequestMapping(value = "initCache", method = "get")
    protected ResultMsg initCache(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        ResultMsg msg = null;
        if (StrUtil.isNull(request.getParameter("sysName"))) {
            msg = new ResultMsg("F", "系统标识不能为空");
            return msg;
        }
        Map<String, String> params = this.getParameterMap(request);
        params.put("doCode", "initCache");
        ResultEntity entity = (ResultEntity) plugin.doInvoke(request, response, params);
        if (StrUtil.isNotNull(String.valueOf(entity.getEntity()))) {
            msg = new ResultMsg("T", String.valueOf(entity.getMessage()));
        } else {
            msg = new ResultMsg("F", entity.getMessage());
        }
        return msg;
    }
}
